package com.customization.test.demo.web;

import com.alibaba.fastjson.JSONObject;
import com.customization.test.demo.service.IRecordSetService;
import com.customization.test.demo.service.impl.IRecordSetServiceImpl;
import com.customization.unionpay.market.util.FormDataUtils;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.cube.biz.ShardingActionHelper;
import com.weaver.formmodel.util.DateHelper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import weaver.conn.RecordSet;
import weaver.formmode.data.ModeDataIDUpdateSingle;
import weaver.formmode.setup.ModeRightInfo;
import weaver.formmode.webservices.ModeDataServiceImpl;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;
import weaver.workflow.webservices.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.*;

import static com.customization.unionpay.market.util.FormDataUtils.createWorkFlow;

public class IRecordSetAction {

    private ModeDataIDUpdateSingle modeDataIDUpdateSingle = ModeDataIDUpdateSingle.INSTANCE;

    private IRecordSetService getService(User user) {
        return ServiceUtil.getService(IRecordSetServiceImpl.class, user);
    }

    @GET
    @Path("/data")
    @Produces({MediaType.TEXT_PLAIN})
    public String weatableDemo(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        try {
            //获取当前用户
            User user = HrmUserVarify.getUser(request, response);
            apidatas.putAll(getService(user).data(ParamUtil.request2Map(request)));
            apidatas.put("api_status", true);

        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);

    }

    @GET
    @Path("/add")
    @Produces({MediaType.TEXT_PLAIN})
    /**
     * 添加建模台账主表
     */
    public String addDemo(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<String, Object>();

        RecordSet recordSet = new RecordSet();
        try {
            //获取当前用户
            User user = HrmUserVarify.getUser(request, response);

            String csr = "1";
            String xb = "1";
            String nl = "1";
            String ah = "2,1";
            String js = "测试下";
            String xgfj = "";
            String bm = "4";
            String csrq = "2024-05-22";
            String gw = "6";
            String cssj = "";

            int formid = -299; // 表单id
            int formmodeid = 264; //模块id

            // 获取主表表名
            String maintablename = getTableName(formid);
            // 先调用内部方法新建一条数据，获取数据id
            int billid = getBillId(maintablename, formmodeid, user.getUID(), user.getType());
            // 获取formbizid
            String formBizId = ShardingActionHelper.constructBizId(billid, formid);

            //获取当前用户
            String addSql = "update uf_csbd set csr='" + csr + "',xb='" + xb + "',nl='" + nl + "',ah='" + ah + "',js='" + js + "',xgfj='" + xgfj + "',bm='" + bm
                    + "',csrq='" + csrq + "',gw='" + gw + "',cssj='" + cssj + "',form_biz_id = '" + formBizId +"' where id = " +billid;
            boolean b = recordSet.executeUpdate(addSql);


            List<JSONObject> files_List = new ArrayList<>();
            JSONObject element = new JSONObject();
            element.put("filename","nginx-1.24.0.tar.gz");
            element.put("filecontent","https://www.baizhanveterans.com/download/nginx-1.24.0.tar.gz");
            files_List.add(element);

            FormDataUtils.resolveFilesElement(formmodeid,user.getUID(),billid,maintablename,files_List,"xgfj");

//            //3、创建编号
//            CodeBuilder cbuild = new CodeBuilder(formmodeid);
//            Map<String, Object> codeFieldMap = cbuild.getModeCodeStr(formid, billid);//生成编号
//            System.out.println(codeFieldMap);
            // 权限重构
            ModeRightInfo modeRightInfo = new ModeRightInfo();
            modeRightInfo.setNewRight(true);
            modeRightInfo.editModeDataShare(1, formmodeid, billid);

            apidatas.put("data", "{'插入状态'：'"+b+"'}");
            apidatas.put("api_status", true);

        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);

    }

    @GET
    @Path("/add2")
    @Produces({MediaType.TEXT_PLAIN})
    public String add2Demo(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> apidatas = new HashMap<String, Object>();

        RecordSet recordSet = new RecordSet();
        try {
            //获取当前用户
            User user = HrmUserVarify.getUser(request, response);

            String pluginDir = GCONST.getRootPath()+"WEB-INF"+ File.separatorChar+"classes"+File.separatorChar+"conf"+File.separatorChar+"plugin"+File.separatorChar;
            System.out.println(pluginDir);

            System.setProperty("magpie.config.file","test001.xml");
//
//            List<String> files = FileUtil.getFiles(pluginDir, ".xml");
//            if(files != null){
//                for(String pluginDefintionPath : files){
//                    System.out.println(pluginDefintionPath);
//                }
//            }
//            File file = FileUtil.getFile(pluginDir+"magpie.xml");

            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("test001.xml");
            System.out.println(applicationContext);


            apidatas.put("data", "{'插入状态'：'1'}");
            apidatas.put("api_status", true);

        } catch (Exception e) {
            e.printStackTrace();
            apidatas.put("api_status", false);
            apidatas.put("api_errormsg", "catch exception : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);

    }

    /**
     * 删除表单数据
     */
    public void deleteModeDataService(){
        ModeDataServiceImpl modeDateService = new ModeDataServiceImpl();
        /**
         @param modeId 模块ID
         @param Id 数据ID
         @param userId 用户ID
         @param right （y/n） 是否受权限控制
          * */
        System.out.println(modeDateService.deleteModeDataById(127, 1, 1, "Y"));
    }

    /**
     * 获取表单数据总数
     */
    public void getAllModeDataCount(){
        ModeDataServiceImpl modeDateService = new ModeDataServiceImpl();
		/*
		 * @param modeId 模块ID
		   @param userId 用户ID
		   @param conditions 查询条件
		   @param right （y/n） 是否受权限控制
		 * */
        System.out.println(modeDateService.getAllModeDataCount(127, 1, "", "Y"));
    }

    /**
     * 获取表单内容
     */
    public void getModeDataByID(){
        ModeDataServiceImpl modeDateService = new ModeDataServiceImpl();
		/*
		 @param modeId 模块ID
		 @param Id 数据ID
		 @param userId 用户ID
		 @param right （y/n） 是否受权限控制
	     @param isReturnDetail （y/n） 是否返回明细表数据
		 * */
        System.out.println(modeDateService.getModeDataByID(127, 3, 1,"Y", "Y"));
    }

    public void getAllModeDataList(){
        ModeDataServiceImpl modeDateService = new ModeDataServiceImpl();
		/*
		 *
		@param modeId 模块ID
		@param pageNo 当前页数
		@param pageSize 每页记录数
		@param recordCount 记录总数（小于等于0时自动计算记录总数）
		@param userid 当前用户
		@param conditions 查询条件
		@param right （y/n） 是否受权限控制
		@param isReturnDetail （y/n） 是否返回明细表数据
		 */
        System.out.println(modeDateService.getAllModeDataList(127, 1, 2,-1,1,"", "Y","N"));
    }

    @GET
    @Path("/startWork")
    public String startWork(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        // api/workflow/paService/doCreateRequest
        JSONObject apidatas = new JSONObject();

        apidatas.put("code", 200);
        apidatas.put("data", null);
        apidatas.put("msg", "发起成功！");
        apidatas.put("errormsg",null);
        try {
            //获取当前用户
            User user = HrmUserVarify.getUser(request, response);

            JSONObject json  = new JSONObject();

            // 文本
            JSONObject js  = new JSONObject();
            js.put("name","js");
            js.put("type","");
            js.put("value","测试");
            json.put("js",js);

            // 选择框（单选）
            JSONObject xb  = new JSONObject();
            xb.put("name","xb");
            xb.put("type","");
            xb.put("value","1");
            json.put("xb",xb);

            int size = json.size() - 1;
//            List<JSONObject> sonData = new ArrayList<>();
//
//            JSONObject singleSonData  = new JSONObject();
//            JSONObject fysm  = new JSONObject();
//            fysm.put("name","fysm");
//            fysm.put("type","");
//            fysm.put("value","测试fysm");
//            singleSonData.put("fysm",fysm);
//            JSONObject fylx  = new JSONObject();
//            fylx.put("name","fylx");
//            fylx.put("type","");
//            fylx.put("value","0");
//            singleSonData.put("fylx",fylx);
//
//            sonData.add(singleSonData);
//
//            json.put("sonData",sonData);

            long currentTimeMillis = System.currentTimeMillis();
            String requestid = createWorkFlow(user, json, size, 0, "23", "0", "0", "测试" + currentTimeMillis);

            if(requestid != null && !requestid.equals("")){
                JSONObject zJson = new JSONObject();
                zJson.put("requestid",requestid);
                apidatas.put("data", zJson);
            }else {
                apidatas.put("code", 500);
                apidatas.put("data", null);
                apidatas.put("msg", "发起失败！");
                apidatas.put("errormsg", "异常");
            }
        } catch (Exception e) {
            apidatas.put("code", 500);
            apidatas.put("data", null);
            apidatas.put("msg", "发起失败！");
            apidatas.put("errormsg", "异常原因 : " + e.getMessage());
        }
        return JSONObject.toJSONString(apidatas);
    }

    public static void createRequest() throws Exception {
        //主字段
        WorkflowRequestTableField[] wrti = new WorkflowRequestTableField[6];
        // 字段信息
        wrti[0] = new WorkflowRequestTableField();
        wrti[0].setFieldName("sqr");
        wrti[0].setFieldValue("14");
        wrti[0].setView(true); // 字段是否可见
        wrti[0].setEdit(true); //字段是否可编辑

        wrti[1] = new WorkflowRequestTableField();
        wrti[1].setFieldName("bm");
        wrti[1].setFieldValue("13");
        wrti[1].setView(true);
        wrti[1].setEdit(true);

        wrti[2] = new WorkflowRequestTableField();
        wrti[2].setFieldName("sqsj");
        wrti[2].setFieldValue("2016-09-01");
        wrti[2].setView(true);
        wrti[2].setEdit(true);

        wrti[3] = new WorkflowRequestTableField();
        wrti[3].setFieldName("xgfj");//附件
        wrti[3].setFieldType("http:baidu_sylogo1.gif|http:126logo.gif");//http:开头代表该字段为附件字段
        wrti[3].setFieldValue("http://www.baidu.com/img/baidu_sylogo1.gif|http://mimg.127.net/logo/126logo.gif");//附件地址
        wrti[3].setView(true);
        wrti[3].setEdit(true);

        wrti[4] = new WorkflowRequestTableField();
        wrti[4].setFieldName("spld");//审批领导
        wrti[4].setFieldValue("3,4");
        wrti[4].setView(true);
        wrti[4].setEdit(true);

        wrti[5] = new WorkflowRequestTableField();
        wrti[5].setFieldName("spsy");//事由
        wrti[5].setFieldValue("这里是个多上多行文本的内容。。。");
        wrti[5].setView(true);
        wrti[5].setEdit(true);

        WorkflowRequestTableRecord[] wrtri = new WorkflowRequestTableRecord[1];//主字段只有一行数据
        wrtri[0] = new WorkflowRequestTableRecord();
        wrtri[0].setWorkflowRequestTableFields(wrti);

        WorkflowMainTableInfo wmi = new WorkflowMainTableInfo();
        wmi.setRequestRecords(wrtri);

        int detailrows = 3 ;//添加指定条数明细
        //添加明细数据
        wrtri = new WorkflowRequestTableRecord[detailrows];//添加指定条数行明细数据
        for(int i = 0 ; i < detailrows ; i++){
            //每行明细对应的字段
            wrti = new WorkflowRequestTableField[4]; //字段信息
            wrti[0] = new WorkflowRequestTableField();
            wrti[0].setFieldName("rq");//单价
            wrti[0].setFieldValue("2016-09-2"+i);
            wrti[0].setView(true);//字段是否可见
            wrti[0].setEdit(true);//字段是否可编辑

            wrti[1] = new WorkflowRequestTableField();
            wrti[1].setFieldName("xh");//数量
            wrti[1].setFieldValue("型号001"+i);
            wrti[1].setView(true);
            wrti[1].setEdit(true);

            wrti[2] = new WorkflowRequestTableField();
            wrti[2].setFieldName("lx");//类型 下拉框
            wrti[2].setFieldValue(""+i);
            wrti[2].setView(true);
            wrti[2].setEdit(true);

            wrti[3] = new WorkflowRequestTableField();
            wrti[3].setFieldName("jg");//价格
            wrti[3].setFieldValue("1"+i+".50");
            wrti[3].setView(true);
            wrti[3].setEdit(true);

            wrtri[i] = new WorkflowRequestTableRecord();
            wrtri[i].setWorkflowRequestTableFields(wrti);
        }

        // 添加到明细表中
        WorkflowDetailTableInfo WorkflowDetailTableInfo[] = new WorkflowDetailTableInfo[1]; //指定明细表的个数，多个明细表指定多个，顺序按照明细的顺序
        WorkflowDetailTableInfo[0] = new WorkflowDetailTableInfo();
        WorkflowDetailTableInfo[0].setWorkflowRequestTableRecords(wrtri);

        //添加工作流id
        WorkflowBaseInfo wbi = new WorkflowBaseInfo();
        wbi.setWorkflowId("38");                             //workflowid 流程接口演示流程2016==38
        WorkflowRequestInfo wri = new WorkflowRequestInfo(); //流程基本信息

        wri.setCreatorId("14");                              //创建人id
        wri.setRequestLevel("2");                            //0 正常，1重要，2紧急

        wri.setRequestName("2016-09-24 001");                //流程标题
        wri.setWorkflowMainTableInfo(wmi);                   //添加主字段数据

        wri.setWorkflowDetailTableInfos(WorkflowDetailTableInfo); //添加明细数据
        wri.setWorkflowBaseInfo(wbi);

        WorkflowServiceImpl  WorkflowServicePortTypeProxy = new WorkflowServiceImpl();
        String requestid = WorkflowServicePortTypeProxy.doCreateWorkflowRequest(wri, 14);

        System.out.println("requestid:"+requestid);
    }

    @POST
    @Path("/zpt")
    @Produces("application/json")
    public JSONObject postDemo(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        JSONObject apidatas = new JSONObject();
        try {

            //获取当前用户
            User user = HrmUserVarify.getUser(request, response);

            String body = readBody(request);
            String key = request.getParameter("key");
            if (body != null) {
                System.out.println("key==>" + key + ",body==>" + body);
                JSONObject parseJson = JSONObject.parseObject(body);
                apidatas.put("data", parseJson);
            }

            apidatas.put("status", true);

        } catch (Exception e) {
            apidatas.put("status", false);
            apidatas.put("errormsg", "catch exception : " + e.getMessage());
        }
        return apidatas;

    }

    private String readBody(HttpServletRequest req) throws IOException {
        if (req.getMethod().equals("POST")) {
            StringBuilder result = new StringBuilder();
            BufferedReader br = req.getReader();
            String line;
            while ((line = br.readLine()) != null) {
                result.append(line);
            }
            br.close();
            return result.toString();
        }
        return null;
    }

    // 获取主表
    public String getTableName(int formid) {
        String maintablename = "";
        String sql = "select * from workflow_bill where id = " + formid;
        RecordSet rs = new RecordSet();
        rs.executeSql(sql);
        while (rs.next()) {
            maintablename = Util.null2String(rs.getString("tablename"));
        };
        return maintablename;
    }

    // 获取查询id，模块id 可能有多个
    public int getSearchId(int formid){
        int id = -1;
        int formmodeid = -1;
        String sql = "select id, from mode_customsearch where formid = " + formid;
        RecordSet rs = new RecordSet();
        rs.executeSql(sql);
        while (rs.next()) {
            id = rs.getInt("id");
            formmodeid = rs.getInt("modeid");
        };
        return id;
    }

    public int getBillId(String billtablename, int formmodeid, int userid, int usertype) {
        int billid = -1;

        String currentdate = DateHelper.getCurrentDate();

        String currenttime = DateHelper.getCurrentTime();
        //取数据库服务器的当前时间
        RecordSet rs = new RecordSet();
        rs.executeProc("GetDBDateAndTime", "");
        if (rs.next()) {
            currentdate = rs.getString("dbdate");
            currenttime = rs.getString("dbtime");
        }
        billid = modeDataIDUpdateSingle.getModeDataNewIdByUUID(billtablename, formmodeid, userid, usertype, currentdate, currenttime);
        return billid;
    }
}
